﻿using System;
using PETimer;
using UnityEngine;

public class AsyncTimerExample : MonoBehaviour {
    public uint interval = 66;
    public int count = 50;

    int sum = 0;
    AsyncTimer timer;
    private void Start() {
        timer = new AsyncTimer(false);
    }

    int tid;
    private void Update() {
        //timer.HandleTask();

        if(Input.GetKeyDown(KeyCode.A)) {
            sum = 0;
            DateTime historyTime = DateTime.UtcNow;
            tid = timer.AddTask(
                interval,
                (int tid) => {
                    DateTime nowTime = DateTime.UtcNow;
                    TimeSpan ts = nowTime - historyTime;
                    historyTime = nowTime;
                    int delta = (int)(ts.TotalMilliseconds - interval);
                    sum += Math.Abs(delta);
                    Extension.Log($"间隔差：{delta}");
                    Extension.Log($"tid:{tid} work.");
                },
                (int tid) => {
                    Extension.Log($"tid:{tid} work.");
                },
                count);
        }

        if(Input.GetKeyDown(KeyCode.Delete)) {
            timer.DeleteTask(tid);
        }
        else if(Input.GetKeyDown(KeyCode.S)) {
            Extension.Log("平均间隔：" + sum * 1.0F / count);
        }
    }
}